package quotation.web.element.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import quotation.exception.BusinessException;
import quotation.web.element.ddd.dto.EleDto;
import quotation.web.element.ddd.entity.ElementEntity;
import quotation.web.element.ddd.form.EleForm;
import quotation.web.element.mapper.ElementMapper;
import quotation.web.element.service.ElementService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lyx
 * @date 2025/2/24
 */
@Service
@Slf4j
public class ElementServiceImpl extends ServiceImpl<ElementMapper, ElementEntity> implements ElementService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAll(EleForm form) {

        Long quotationSysId = form.getQuotationSysId();
        List<EleDto> dtoList = form.getDtoList();

        this.vaildEle(form);

        List<ElementEntity> collect = dtoList.parallelStream().map(t -> {
            ElementEntity elementEntity = BeanUtil.copyProperties(t, ElementEntity.class);
            elementEntity.setQuotationSysId(quotationSysId);

            return elementEntity;
        }).collect(Collectors.toList());

        this.saveBatch(collect);


    }

    @Override
    public List<ElementEntity> get(Long id) {
        List<ElementEntity> list = this.lambdaQuery()
                .eq(ElementEntity::getQuotationSysId, id)
                .list();
        return list;
    }

    public void vaildEle(EleForm form) {

        Long quotationSysId = form.getQuotationSysId();
        List<ElementEntity> list = this.lambdaQuery()
                .eq(ElementEntity::getQuotationSysId, quotationSysId)
                .list();

        Set<String> keySet = new HashSet<>();

        if (CollUtil.isNotEmpty(list)) {
            Set<String> collect = list.parallelStream().map(ElementEntity::getKey).collect(Collectors.toSet());
            keySet.addAll(collect);
        }

        List<EleDto> dtoList = form.getDtoList();
        Set<String> collect = dtoList.parallelStream().map(EleDto::getKey).collect(Collectors.toSet());

        if (collect.size() != dtoList.size()) {
            throw new BusinessException("存在相同的key，请检查");
        }

        if (CollUtil.isNotEmpty(keySet)) {
            List<String> collected = collect.parallelStream().filter(keySet::contains).collect(Collectors.toList());
            throw new BusinessException("key为" + collected + "已存在");
        }

    }

}
